import { SupplierService } from 'src/app/@core/services/supplier/supplier.service';
import { DirctoryService } from './../../../../../@core/services/dirctory/dirctory.service';
import { Router } from '@angular/router';
import { StorehouseService } from './../../../../../@core/services/storehouse/storehouse.service';
import { MaterialService } from './../../../../../@core/services/material/material.service';
import { EncodeRulesService } from './../../../../../@core/services/encoderRule/encode-rules.service';
import { Component, ViewChild } from '@angular/core';
import { CascaderItem, DValidateRules, FileUploader, FormLayout, IFileOptions, IUploadOptions, DialogService } from 'ng-devui';
import { environment } from 'src/environments/environment';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { SelectSupplierComponent } from 'src/app/@shared/components/select-supplier/select-supplier.component';
@Component({
  selector: 'app-add-material',
  templateUrl: './add-material.component.html',
  styleUrls: ['./add-material.component.scss']
})
export class AddMaterialComponent {
  msg: any;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  options: any = [];
  allUnits: any = [];
  Material = {
    partName: '',
    partNum: '',
    englishName: '',
    partType: '',
    mnemonicCode: '',
    partClassid: null,
    description: '',
    fileURL: '',
    costPrice: null,
    salePrice: null,
    partProperty: '',
    partUOM: '',
    minimumStock: null,
    maximumStock: null,
    safetyInventory: null,
    warehouseID: null,
    positionID: null,
    addFileURL: '',
    supplyId: null,
    supplyName: '',
    supplyNum: '',
    isInspection:false,
  }
  msgs: Array<Object> = [];
  option: Array<number> = [];//物料分类
  allWarehouses: Array<number> = [] //所有仓库
  allPositions: Array<number> = [] //所有库位
  message: Array<Object> = [];
  uploadedFiles: Array<Object> = [];
  fileUploaders: Array<FileUploader> = [];
  isDropOver = false;
  uploadOptions: IUploadOptions = {
    uri: environment.apiUrl + '/Part/UploadAvatar',
    maximumSize: 1024,
    method: 'post',
    checkSameName: true,
    fileFieldName: "file",
  };
  uploadOptions2: IUploadOptions = {
    uri: environment.apiUrl + '/Part/UploadAttachment',
    method: 'post',
    maximumSize: 20,
    checkSameName: true
  };
  fileOptions: IFileOptions = {
    multiple: true,
    accept: '.png,.jpg,.jpeg,.gif,.bmp,.wbmp,.webp',
  };
  fileOptions2: IFileOptions = {
    multiple: true,
  };
  UPLOADED: string;
  CANCELUPLOAD: string;
  materialHeaderUrl: any;
  MaterialRules: { [key: string]: DValidateRules } = {
    partNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料编码不能为空' },
        { minlength: 2, message: '*物料编码长度至少为2' },
        { maxlength: 40, message: '*物料编码长度至多为40' },
      ],
    },
    partName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料名称不能为空' },
        { maxlength: 40, message: '*物料名称长度至多为40' },
            ],
    },
    englishName: {
      messageShowType: 'text',
      validators: [
        { maxlength: 40, message: '*英文名称长度至多为40' }
            ],
    },
    partType: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料规格不能为空' },
        { maxlength: 40, message: '*物料规格长度至多为40' }      ],
    },
    mnemonicCode: {
      messageShowType: 'text',
      validators: [
        { maxlength: 40, message: '*助记码长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*助记码不能包含空格' }
      ],
    },
    partClassid: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料类别不能为空' },
      ],
    },
    wareName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*仓库不能为空' },
      ],
    },
    positionName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*库位不能为空' },
      ],
    },
    description: {
      messageShowType: 'text',
      validators: [
        { maxlength: 200, message: '*物料描述长度至多为200' }
      ],
    },
    costPrice: {
      messageShowType: 'text',
      validators: [
        { pattern: /^(?!0(\.0+)?$)(\d+(\.\d{1,})?)$/, message: '*成本价必须大于0' }
      ],
    },
    salePrice: {
      messageShowType: 'text',
      validators: [
        { pattern: /^(?!0(\.0+)?$)(\d+(\.\d{1,})?)$/, message: '*销售价必须大于0' }
      ],
    },
    partProperty: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料属性不能为空' },
      ],
    },
    partUOM: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料单位不能为空' },
      ],
    },
    minimumStock: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*最小库存不能为空' },
        { pattern: /^[1-9][0-9]*$/, message: '*最小库存只能为数字' }
      ],
    },
    maximumStock: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*最大库存不能为空' },
        { pattern: /^[1-9][0-9]*$/, message: '*最大库存只能为数字' }
      ],
    },
    safetyInventory: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*安全库存不能为空' },
        { pattern: /^[1-9][0-9]*$/, message: '*安全库存只能为数字' }
      ],
    },

  }
  file: any;
  constructor(private EncodeRulesService: EncodeRulesService, private MaterialService: MaterialService, private StorehouseService: StorehouseService, private Router: Router, private DirctoryService: DirctoryService, private DialogService: DialogService, private SupplierService: SupplierService) {
    this.UPLOADED = '上传成功';
    this.CANCELUPLOAD = '取消上传';
  }
  ngOnInit(): void {
    this.EncodeRulesService.GenerateWarehouseCodeRule('物料编码','物料编码').subscribe((res: any) => {
      this.Material.partNum = res;
    });
    this.MaterialService.getPartClassesWithChildren(1, 999).subscribe((res: any) => {
      this.options = this.convertToCascaderItem(res.items);
    });
    this.StorehouseService.getAllWarehouses().subscribe((res: any) => {
      this.allWarehouses = res
    })
    this.DirctoryService.getDictionaryEntriesByCategoryName("物料单位").subscribe((res: any) => {
      this.allUnits = res.value
    })
  }
  convertToCascaderItem(data: any[]): CascaderItem[] {
    return data.map(item => {
      let cascaderItem: CascaderItem = {
        label: item.partClassName,
        value: item.partClassId,
      };
      if (item.subPartClasses) {
        cascaderItem.children = this.convertToCascaderItem(item.subPartClasses);
      }
      return cascaderItem;
    });
  }//转换数据格式为华为库练级菜单的数据格式
  CascaderonChanges($event: any) {
    this.Material.partClassid = $event[$event.length - 1]
  }
  wareHouseChanges($event: any) {
    this.Material.warehouseID = $event.warehouseId
    if (this.Material.warehouseID) {
      this.StorehouseService.getWarehousePositionsByWarehouseId(this.Material.warehouseID, 1, 999).subscribe((res: any) => {
        this.allPositions = res.items
      })
    }
  }//选择仓库
  PositionChanges($event: any) {
    this.Material.positionID = $event.positionId
  }//选择库位
  submit($event:any ) {
    if ($event.valid) {
      this.MaterialService.createPart(this.Material).subscribe((res: any) => {
        this.showToast('success', '成功', '创建成功')
        setTimeout(() => {
          this.Router.navigate(['/pages/basicdata/material'])
        }, 1500);
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
      )
    }else{
      this.showToast('warning','失败','请按照要求填写表单')
    }
  }
  materialHeaderUrls: string[] = [];
  onSuccess(event: any) {
    const repsonse = event.map((item: { response: string; }) => JSON.parse(item.response).avatarUrl);
    this.materialHeaderUrls = repsonse
    const trimmedUrls = repsonse.map((url: string) => url.replace(environment.modifiedApiUrl, ""));
    const resultString = trimmedUrls.join(',');
    if (this.Material.fileURL) {
      this.Material.fileURL += ',' + resultString;
    } else {
      this.Material.fileURL = resultString;
    }
  }//上传成功
  fileDrop(files: any) {
    this.isDropOver = false;
  }
  fileOver(event: boolean) {
    this.isDropOver = event;
  }
  deleteFile(currFile: FileUploader) {
    this.fileUploaders = this.fileUploaders.filter((fileUploader) => {
      return currFile !== fileUploader;
    });
    const responseObj = this.fileUploaders.map(item => JSON.parse(item.response).avatarUrl);
    this.materialHeaderUrls = responseObj
    const trimmedUrls = responseObj.map((url: string) => url.replace(environment.modifiedApiUrl, ""));
    const resultString = trimmedUrls.join(',');
    this.Material.fileURL = resultString;
  }
  cancle() {
    this.Router.navigate(['/pages/basicdata/material'])
  }
  unitChanges($event: any) {
    this.Material.partUOM = $event.unitName
  }
  getImagesArray(fileURL: string): string[] {
    if (!fileURL) {
      return [];
    }
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl + url);
    return urls;
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  onButtonClick(dialogtype?: string) {
    const results = this.DialogService.open({
      title: '物料附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '物料附件',
        urls: this.Material.addFileURL
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.Material.addFileURL = results.modalContentInstance.urls;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectSupplier(dialogtype?: string) {
    const results = this.DialogService.open({
      title: '选择供应商',
      width: '1200px',
      backdropCloseable: false,
      content: SelectSupplierComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.selectData) {
              this.Material.supplyId = results.modalContentInstance.selectData.supplyId;
              this.Material.supplyName = results.modalContentInstance.selectData.supplyChineseName;
              this.Material.supplyNum = results.modalContentInstance.selectData.supplyNum;
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  gerFileNum(fileURL: string): number {
    if(fileURL === null || fileURL === '') {
      return 0;
    }
    return fileURL.split(',').length;
  }
}
